package service.impl;

import Dto.GoodsDto;
import dao.OrderDAO;
import dao.impl.AddressDaoImpl;
import dao.impl.OrderDAOImpl;
import model.Address;
import model.Order;
import model.User;
import model.common.Entity;
import service.OrderService;

import java.sql.Connection;
import java.util.Date;

public class OrderServiceImpl implements OrderService {

    private final OrderDAO orderDAO = new OrderDAOImpl();

    @Override
    public int addOrder(User user, GoodsDto goodsDto) {
        Order order = new Order();
        order.setId(Entity.getUUID());
        order.setSerialNumber(Entity.getUUID());
        order.setUserId(user.getId());
        order.setAmount(goodsDto.getNum() * goodsDto.getPrice());
        order.setConsignee(user.getUsername());
        order.setPhone(user.getPhone());
        order.setState(goodsDto.getState());
        order.setConsigneeAddress(new AddressDaoImpl().getUserDefaultAddress(user).getAddress());
        order.setCreateTime(new Date());
        try {
            // 添加主订单
            orderDAO.addOrder(order);
            // 添加附加订单
            orderDAO.addOrderDetail(order, goodsDto);
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
        return 1;
    }


    @Override
    public int addOrder(Connection con, User user, GoodsDto goodsDto) {
        Order order = new Order();
        order.setId(Entity.getUUID());
        order.setSerialNumber(Entity.getUUID());
        order.setUserId(user.getId());
        order.setAmount(goodsDto.getNum() * goodsDto.getPrice());
        order.setConsignee(user.getUsername());
        order.setPhone(user.getPhone());
        order.setState(goodsDto.getState());
        Address address = new AddressDaoImpl().getUserDefaultAddress(user);
        if (null != address) order.setConsigneeAddress(address.getAddress());
        else order.setConsigneeAddress("null");
        order.setCreateTime(new Date());
        try {
            // 添加主订单
            orderDAO.addOrder(con, order);
            // 添加附加订单
            orderDAO.addOrderDetail(order, goodsDto);
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
        return 1;
    }
}
